package com.example.fenye.controller;

import com.example.fenye.argResolver.PagerSpec;
import com.example.fenye.entity.User;
import com.example.fenye.service.UserService;
import com.example.fenye.util.PagerUtil;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Iterator;

/**
 * Created by Administrator on 2018/5/14.
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping(value = "/showUser", produces = {"application/json;charset=UTF-8"})
    public User selectUser(User user){
        User a = userService.selectUser(1);
        return a;
    }

//    @ResponseBody
    @GetMapping("/all")
    public ModelAndView findAllUser(PagerSpec pagerSpec
//            ,
//            @RequestParam(name = "pageNum", required = false, defaultValue = "1")
//            int pageNum,
//            @RequestParam(name = "pageSize", required = false, defaultValue = "10")
//            int pageSize
    ){
        //开始分页

//        return userService.findAllUser(pagerSpec.getCurrentPage(), pagerSpec.getPerPageNum());

        ModelAndView mav = new ModelAndView("user/userlist");
        pagerSpec.setTotalItems(userService.findAllUser(0, 0).size());  //获取totalItems数目


        mav.addObject("userlist",userService.findAllUser(pagerSpec.getCurrentPage(), pagerSpec.getPerPageNum()) );
        mav.addObject("pagerSpec", PagerUtil.calculatePagerSpec(pagerSpec));    //根据pagerSpec的一些数据完善余下的数据，根据 totalItems 共多少条、perPageNum 每页条数，计算 totalPage 共有多少页
        return mav;
    }

    @GetMapping(value = "/toadduser")
    public ModelAndView toAddUser(){
        ModelAndView mav = new ModelAndView("user/adduser");
        return mav;
    }

    @RequestMapping(value="/adduser", method = RequestMethod.POST)
    public ModelAndView addUser(User user, MultipartHttpServletRequest request, HttpServletResponse response){
        ModelAndView mav = new ModelAndView(new MappingJackson2JsonView(), null);
        Iterator<String> fileFieldIt = request.getFileNames();
        String fileField;
        MultipartFile file;
        while(fileFieldIt.hasNext()) {
            fileField = fileFieldIt.next();
            file = request.getFile(fileField);
//            File fileWrite= new File("g:\\temp\\2018-5-21\\"+fileField);
//            if (!fileWrite.exists()) {
//                try {
//                    fileWrite.getParentFile().mkdirs();//构建文件夹
//                    fileWrite.createNewFile();//构建文件
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }

            //拼接成完整的指定的文件路径名，创建新文件
            String filePath = "g:\\temp\\2018-5-21\\"+file.getOriginalFilename();
            File targetfile = new File(filePath);
            if(targetfile.exists()){
                targetfile.delete();
            }

            InputStream is=null;
            OutputStream os=null;
            try {
                //使用输入流读取前台的file文件
                is = file.getInputStream();

                //循环读取输入流文件内容，通过输出流将内容写入新文件
                os = new FileOutputStream(targetfile);
                byte buffer[] = new byte[8192];
                int cnt = 0;
                while ((cnt = is.read(buffer)) > 0) {
                    os.write(buffer, 0, cnt);
                }
            }catch(Exception e) {
                e.printStackTrace();

            }finally {
                //关闭输入输出流
                try {
                    if(os!=null) {
                        os.flush();
                        os.close();
                    }
                    if(is!=null){
                        is.close();
                    }
                }catch(Exception e){

                }

            }
        }
        mav.addObject("success","true");
        return mav;
    }
}
